require 'GameState.GameStateBase'

---@class ReconnectGameState @游戏状态父类
ReconnectGameState = class("ReconnectGameState", GameStateBase)
ReconnectGameState.MAX_PING_INTERVAL = 15

function ReconnectGameState:onBegin()
    EVTM.add(EVENT.SYS_TCP_CONNECT_FINISH, self.onTcpConnect, self)
    EVTM.add(EVENT.SYS_TCP_DISCONNECTED, self.onDisconnect, self)
    EVTM.add(EVENT.SYS_TCP_RECEIVE_MSG..tostring(MsgType.PING), ReconnectGameState.onReceivePing, self)
    EVTM.add(EVENT.SYS_TCP_RECEIVE_ERR..tostring(MsgType.RECONNECT_RESPONSE), ReconnectGameState.onReconnectError, self)
    self.connected = true
    self.pingRecvTime = 0
end

function ReconnectGameState:onReceivePing()
    self.pingRecvTime = 0
end

function ReconnectGameState:fixedUpdate()
    self.pingRecvTime = self.pingRecvTime + Time.fixedDeltaTime
    if self.connected and self.pingRecvTime >= ReconnectGameState.MAX_PING_INTERVAL then
        print('PING TIMEOUT DISCONNECT')
        self.connected = false
        self.pingRecvTime = 0
        Channels.TcpChannel.tcpChannel:Close()
        Channels.TcpChannel:OnDisconnect()
    end
end

function ReconnectGameState:onEnd()
    EVTM.remove(EVENT.SYS_TCP_CONNECT_FINISH, self.onTcpConnect, self)
    EVTM.remove(EVENT.SYS_TCP_DISCONNECTED, self.onDisconnect, self)
    EVTM.remove(EVENT.SYS_TCP_RECEIVE_MSG..tostring(MsgType.PING), ReconnectGameState.onReceivePing, self)
    EVTM.remove(EVENT.SYS_TCP_RECEIVE_ERR..tostring(MsgType.RECONNECT_RESPONSE), ReconnectGameState.onReconnectError, self)
end

function ReconnectGameState:onDisconnect()
    self.connected = false
    Channels.TcpChannel:Connect(config.GAME_TCP_HOST, config.GAME_TCP_PORT)
end

function ReconnectGameState:onTcpConnect()
    self.pingRecvTime = 0
    self.connected = true
    local msg = Login.Reconnect()
    msg.playerId = MyPlayerId
    msg.conv = config.GAME_KCP_CONV
    Channels.TcpChannel:Send(MsgType.RECONNECT_REQ,msg:SerializeToString())
end

function ReconnectGameState:onReconnectError(param)
    gameMgr:changeState('ProcRestarting')
end